﻿using System;
using Enyim.Caching;
using System.Web.Mvc;
using SilenthinkContract;
using Web.Areas.My.Models;
using SilenthinkContract.Domain;
using SilenthinkCommon.Extension;
using SilenthinkContract.Component;
using SilenthinkCommon.Components;

namespace Web.Areas.My.Controllers
{
    public class SecurityController : MyBaseController
    {
        private const string SecuritySessionKey = "security.session.key";


        public SecurityController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient) : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        public ActionResult Index()
        {
            var model = new SecurityControllerModel.Index();
            var identity = User.Identity.SkIdentity();
            model.User = PassportService.GetUser(identity.Id);
            return View(model);
        }

        public ActionResult ChangePassword()
        {
            return View();
        }
        [HttpPost]
        public ActionResult ChangePassword(string oldPassword, string newPassword)
        {
            var identity = User.Identity.SkIdentity();
            var result = new SkResult<string>(false);

            if (string.IsNullOrEmpty(oldPassword))
            {
                result.Data = "oldpwd";
                result.Message = "请输入原密码!";

                return Json(result);
            }
            //if (!newPwd.IsPassword())
            //{
            //    result.Data = "newpwd";
            //    result.Message = "请输入新密码!";

            //    return Json(result);
            //}
            //if (newPwd != confirmPwd)
            //{
            //    result.Data = "confirmpwd";
            //    result.Message = "确认密码与新密码不一致!";

            //    return Json(result);
            //}
            var user = PassportService.GetUser(identity.Id);
            if (user != null)
            {
                var password = (newPassword.ToPassword() + PasswordSalt).ToPassword();
                if (password == user.Password)
                {
                    result.Message = "新密码不能与原密码一样！";
                }
                else
                {
                    result.Status = PassportService.ChangePassword(identity.Id, password);
                    if (!result.Status)
                    {
                        result.Message = "修改密码失败！";
                    }
                }
            }
            return Json(result);
        }

        #region 邮箱绑定
        /// <summary>
        /// 邮箱绑定
        /// </summary>
        /// <returns></returns>
        public ActionResult EmailBinding()
        {
            return PartialView();
        }

        /// <summary>
        /// 邮箱绑定
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EmailBinding(string email)
        {
            var guid = Guid.NewGuid();

            var result = new SkResult<string>();
            var identity = User.Identity.SkIdentity();

            if (!email.IsEmail())
            {
                result.Message = "请输入正确的邮箱！如：example@silenthink.com";
            }
            else
            {
                var exist = PassportService.ExistBindingEmail(email);
                if (exist)
                {
                    result.Message = "该电子邮箱已绑定其它帐号，请换个邮箱！";
                }
                else
                {
                    // todo 发送邮箱绑定邮件
                    var log = new EmailVerification();
                    var authCode = email.AesEncrypt(AesKey);
                    log.Id = guid;
                    log.UserId = identity.Id;
                    log.Email = email;
                    log.Category = 3;
                    log.AuthCode = authCode;
                    log.CreatedBy = "sys.emailbing";
                    log.CreatedOn = DateTime.Now;
                    var status = ExtraService.CreateEmailVerification(log);
                    if (status)
                    {
                        result.Status = true;
                    }
                    else
                    {
                        result.Message = "发送邮件失败！";
                    }
                }
            }
            return Json(result);
        }

        /// <summary>
        /// 验证邮箱绑定
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ActionResult ValidateEmailBinding(string param)
        {
            var result = new SkResult<string>();
            var identity = User.Identity.SkIdentity();
            var log = ExtraService.GetEmailVerification(param, 3, identity.Id);
            if (log == null)
            {
                result.Message = "链接无效或已过期！";
            }
            else
            {
                var status = PassportService.EmailBinding(identity.Id, log.Email);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "绑定邮箱失败，请重试！";
                }
            }
            return View(result);
        }

        #endregion

        #region 手机绑定
        /// <summary>
        /// 手机绑定
        /// </summary>
        /// <returns></returns>
        public ActionResult MobileBinding()
        {
            return PartialView();
        }

        /// <summary>
        /// 手机绑定
        /// </summary>
        /// <param name="mobile">手机号码</param>
        /// <param name="smsCode">短信验证码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult MobileBinding(string mobile, string smsCode)
        {
            var result = new SkResult<string>();
            var identity = User.Identity.SkIdentity();
            if (!mobile.IsMobile() || smsCode.IsNullOrEmpty())
            {
                result.Message = "手机号码不正确或短信验证码为空！";
                return Json(result);
            }
            var log = ExtraService.GetSmsVerification(smsCode, mobile, 3, identity.Id);
            if (log == null || mobile != log.Mobile)
            {
                result.Message = "短信验证码不正确或已过期！";
                return Json(result);
            }
            var exist = PassportService.ExistBindingMobile(mobile);
            if (!exist)
            {
                var status = PassportService.MobileBinding(identity.Id, log.Mobile);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "绑定手机失败，请重试！";
                }
            }
            else
            {
                result.Message = "该手机号码已绑定其它帐号，请换个手机号码！";
            }
            return Json(result);
        }

        /// <summary>
        /// 发送手机绑定短信
        /// </summary>
        /// <param name="mobile">手机号码</param>
        /// <returns></returns>
        public ActionResult SmsCode(string mobile)
        {
            var guid = Guid.NewGuid();
            var result = new SkResult<string>();
            var identity = User.Identity.SkIdentity();
            if (!mobile.IsMobile())
            {
                result.Message = "请输入正确的手机号码！";
                return Json(result);
            }
            var exist = PassportService.ExistBindingMobile(mobile);
            if (!exist)
            {
                var log = new SmsVerification();
                var bytes = Utility.GenerateRandomNumber(3);
                log.Id = guid;
                log.UserId = identity.Id;
                log.Category = 3;
                log.Mobile = mobile;
                log.SmsCode = bytes.ToHex();
                log.CreatedBy = "sys.mobilebinding";
                log.CreatedOn = DateTime.Now;
                var status = ExtraService.CreateSmsVerification(log);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "发送手机验证码失败，请重试！";
                }
            }
            else
            {
                result.Message = "该手机号码已绑定其它帐号，请换个手机号码！";
            }
            return Json(result);
        }

        #endregion
    }
}
